<template>
  <el-card class="card-box">
    <div class="header">
      <h2>设备维护记录管理</h2>
    </div>

    <el-tabs v-model="activeTab" @tab-change="handleTabChange">
      <el-tab-pane label="维护记录上传" name="upload">
        <el-form inline class="filter-bar">
          <el-form-item label="设备ID:" class="filter-item">
            <el-select
              v-model="searchParams.serialNumber"
              filterable remote clearable reserve-keyword
              placeholder="请输入设备ID"
              :remote-method="fetchSerialSuggestions"
              :loading="loadingSerialNumbers"
            >
              <el-option
                v-for="item in serialNumberOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item class="filter-item action-buttons">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>

        <div class="responsive-table-container">
          <table class="custom-table">
            <thead>
              <tr>
                <th>编号</th>
                <th>设备ID</th>
                <th>维护周期(天)</th>
                <th>维护内容</th>
                <th>下次维护时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="item in maintenancePlans" :key="item.id">
                <td>{{ item.id }}</td>
                <td>{{ item.serialNumber }}</td>
                <td>{{ item.cycle }}</td>
                <td class="truncate">{{ item.content }}</td>
                <td>{{ item.nextMaintenanceTime }}</td>
                <td>
                  <div class="action-btns">
                    <el-button
                      :icon="Plus"
                      circle
                      plain
                      size="small"
                      type="primary"
                      @click="handleAddRecord(item)"
                    />
                    <el-button
                      :icon="View"
                      circle
                      plain
                      size="small"
                      type="info"
                      @click="handleViewRecords(item)"
                    />
                  </div>
                </td>
              </tr>
              <tr v-if="maintenancePlans.length === 0">
                <td colspan="6" class="text-center py-4">
                  <el-empty description="暂无数据" />
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :page-sizes="[5, 10, 20]"
            layout="total, sizes, prev, pager, next, jumper"
            background
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </el-tab-pane>

      <el-tab-pane label="维护历史查看" name="history">
        <el-form inline class="filter-bar">
          <el-form-item label="设备ID:" class="filter-item">
            <el-select
              v-model="searchParams.serialNumber"
              filterable remote clearable reserve-keyword
              placeholder="请输入设备ID"
              :remote-method="fetchSerialSuggestions"
              :loading="loadingSerialNumbers"
            >
              <el-option
                v-for="item in serialNumberOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="维护人:" class="filter-item">
            <el-input
              v-model="searchParams.maintainerName"
              placeholder="请输入维护人姓名"
              clearable
            />
          </el-form-item>
          <el-form-item class="filter-item action-buttons">
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>

        <div class="responsive-table-container">
          <table class="custom-table">
            <thead>
              <tr>
                <th>编号</th>
                <th>计划ID</th>
                <th>设备ID</th>
                <th>维护人</th>
                <th>维护时间</th>
                <th>维护内容</th>
                <th>维护费用</th>
                <th>备注</th>
                <th>记录时间</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="item in maintenanceRecords" :key="item.id">
                <td>{{ item.id }}</td>
                <td>{{ item.planId }}</td>
                <td>{{ item.serialNumber }}</td>
                <td>{{ item.maintainerName }}</td>
                <td>{{ item.maintenanceTime }}</td>
                <td class="truncate">{{ item.maintenanceContent }}</td>
                <td>{{ item.cost }}</td>
                <td class="truncate">{{ item.remarks }}</td>
                <td>{{ item.recordTime }}</td>
              </tr>
              <tr v-if="maintenanceRecords.length === 0">
                <td colspan="9" class="text-center py-4">
                  <el-empty description="暂无维护记录" />
                </td>
              </tr>
            </tbody>
          </table>
        </div>

        <div class="pagination-container">
          <el-pagination
            v-model:current-page="pageNum"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50]"
            layout="total, sizes, prev, pager, next, jumper"
            background
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 添加维护记录对话框 -->
    <el-dialog
      v-model="showRecordForm"
      :title="isEdit ? '编辑维护记录' : '添加维护记录'"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form :model="recordFormModel" label-width="120px" class="drawer-form">
        <el-form-item label="计划ID:" v-if="recordFormModel.planId">
          <el-tag>{{ recordFormModel.planId }}</el-tag>
        </el-form-item>
        <el-form-item label="设备ID:" v-if="recordFormModel.serialNumber">
          <el-tag>{{ recordFormModel.serialNumber }}</el-tag>
        </el-form-item>

        <el-form-item label="维护人:" required>
          <el-input
            v-model="recordFormModel.maintainerName"
            placeholder="请输入维护人姓名"
          />
        </el-form-item>

        <el-form-item label="维护时间:" required>
          <el-date-picker
            v-model="recordFormModel.maintenanceTime"
            type="datetime"
            placeholder="请选择维护时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="维护内容:" required>
          <el-input
            v-model="recordFormModel.maintenanceContent"
            type="textarea"
            :rows="3"
            placeholder="请输入维护内容"
          />
        </el-form-item>

        <el-form-item label="维护费用:">
          <el-input
            v-model="recordFormModel.cost"
            placeholder="请输入维护费用"
            type="number"
          />
        </el-form-item>

        <el-form-item label="备注:">
          <el-input
            v-model="recordFormModel.remarks"
            type="textarea"
            :rows="2"
            placeholder="请输入备注信息"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSubmitRecord" :loading="isSubmitting">
            {{ isSubmitting ? '提交中...' : '提交' }}
          </el-button>
          <el-button @click="showRecordForm = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 查看维护记录对话框 -->
    <el-dialog
      v-model="showRecordDialog"
      title="维护记录详情"
      width="80%"
      top="5vh"
    >
      <div class="responsive-table-container">
        <table class="custom-table">
          <thead>
            <tr>
              <th>编号</th>
              <th>计划ID</th>
              <th>设备ID</th>
              <th>维护人</th>
              <th>维护时间</th>
              <th>维护内容</th>
              <th>维护费用</th>
              <th>备注</th>
              <th>记录时间</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in planRecords" :key="item.id">
              <td>{{ item.id }}</td>
              <td>{{ item.planId }}</td>
              <td>{{ item.serialNumber }}</td>
              <td>{{ item.maintainerName }}</td>
              <td>{{ item.maintenanceTime }}</td>
              <td class="truncate">{{ item.maintenanceContent }}</td>
              <td>{{ item.cost }}</td>
              <td class="truncate">{{ item.remarks }}</td>
              <td>{{ item.recordTime }}</td>
            </tr>
            <tr v-if="planRecords.length === 0">
              <td colspan="9" class="text-center py-4">
                <el-empty description="该计划暂无维护记录" />
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </el-dialog>
  </el-card>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { View, Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import { useTokenStore } from '@/stores/token'

const tokenStore = useTokenStore()

interface MaintenancePlan {
  id: number
  serialNumber: string
  creatorId: number
  cycle: number
  content: string
  nextMaintenanceTime: string
  createTime: string
  updateTime: string
}

interface MaintenanceRecord {
  id: number
  planId: number
  serialNumber: string
  maintainerId: number
  maintainerName: string
  maintenanceTime: string
  maintenanceContent: string
  cost: number | null
  remarks: string | null
  recordTime: string
}

interface MaintenancePlanListResponse {
  current: number
  total: number
  pages: number
  size: number
  records: MaintenancePlan[]
}

interface MaintenanceRecordListResponse {
  current: number
  total: number
  pages: number
  size: number
  records: MaintenanceRecord[]
}

interface MaintenanceRecordModel {
  planId: number | null
  serialNumber: string | null
  maintainerId: number | null
  maintainerName: string | null
  maintenanceTime: string | null
  maintenanceContent: string | null
  cost: number | null
  remarks: string | null
}

const maintenanceApi = {
  getPlanList: (params: any) => request<MaintenancePlanListResponse>({
    method: 'GET',
    url: '/maintenance/plan/page',
    params
  }),
  getRecordList: (params: any) => request<MaintenanceRecordListResponse>({
    method: 'GET',
    url: '/maintenance/record/page',
    params
  }),
  addRecord: (data: MaintenanceRecordModel) => request<string>({
    method: 'POST',
    url: '/maintenance/record',
    data
  }),
  updateRecord: (id: number, data: MaintenanceRecordModel) => request<string>({
    method: 'PUT',
    url: `/maintenance/record/${id}`,
    data
  }),
  getSerialSuggestions: (keyword: string) => request<string[]>({
    method: 'GET',
    url: '/device/serial/suggestions',
    params: { keyword }
  })
}

const maintenancePlans = ref<MaintenancePlan[]>([])
const maintenanceRecords = ref<MaintenanceRecord[]>([])
const planRecords = ref<MaintenanceRecord[]>([])
const serialNumberOptions = ref<string[]>([])
const loadingSerialNumbers = ref(false)

const recordFormModel = ref<MaintenanceRecordModel>({
  planId: null,
  serialNumber: null,
  maintainerId: tokenStore.id || null,
  maintainerName: tokenStore.userName || null,
  maintenanceTime: null,
  maintenanceContent: null,
  cost: null,
  remarks: null
})

const searchParams = ref({
  serialNumber: null as string | null,
  maintainerName: null as string | null
})

const loading = ref(false)
const isSubmitting = ref(false)
const showRecordForm = ref(false)
const showRecordDialog = ref(false)
const isEdit = ref(false)
const editingId = ref<number | null>(null)

const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const activeTab = ref('upload')

// const tableRowClassName = ({ rowIndex }: { rowIndex: number }) => {
//   if (rowIndex % 4 === 0) return 'warning-row'
//   if (rowIndex % 4 === 2) return 'success-row'
//   return ''
// }

onMounted(async () => {
  await fetchMaintenancePlans()
})

const fetchSerialSuggestions = async (query: string) => {
  if (query) {
    loadingSerialNumbers.value = true
    try {
      const res = await maintenanceApi.getSerialSuggestions(query)
      serialNumberOptions.value = res.data
    } catch {
      ElMessage.error('获取设备序列号失败')
    } finally {
      loadingSerialNumbers.value = false
    }
  } else {
    serialNumberOptions.value = []
  }
}

const fetchMaintenancePlans = async () => {
  loading.value = true
  try {
    const params = {
      page: pageNum.value,
      size: pageSize.value,
      serialNumber: searchParams.value.serialNumber
    }
    const response = await maintenanceApi.getPlanList(params)
    maintenancePlans.value = response.data.records
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('获取维护计划列表失败')
  } finally {
    loading.value = false
  }
}

const fetchMaintenanceRecords = async () => {
  loading.value = true
  try {
    const params = {
      page: pageNum.value,
      size: pageSize.value,
      serialNumber: searchParams.value.serialNumber,
      maintainerName: searchParams.value.maintainerName
    }
    const response = await maintenanceApi.getRecordList(params)
    maintenanceRecords.value = response.data.records
    total.value = response.data.total
  } catch (error) {
    ElMessage.error('获取维护记录列表失败')
  } finally {
    loading.value = false
  }
}

const fetchPlanRecords = async (planId: number) => {
  loading.value = true
  console.log('planId'+planId)
  try {
    const response = await maintenanceApi.getRecordList({ 
      page: 1, 
      size: 100, 
      planId,
    })
    planRecords.value = response.data.records
    showRecordDialog.value = true
  } catch (error) {
    ElMessage.error('获取维护记录失败')
  } finally {
    loading.value = false
  }
}

const handleAddRecord = (plan: MaintenancePlan) => {
  isEdit.value = false
  editingId.value = null
  recordFormModel.value = {
    planId: plan.id,
    serialNumber: plan.serialNumber,
    maintainerId: tokenStore.id || 1,
    maintainerName: tokenStore.userName || '',
    maintenanceTime: new Date().toISOString(),
    maintenanceContent: plan.content,
    cost: null,
    remarks: null
  }
  showRecordForm.value = true
}

const handleViewRecords = (plan: MaintenancePlan) => {
  fetchPlanRecords(plan.id)
}

const handleSubmitRecord = async () => {
  if (isSubmitting.value) return

  if (!recordFormModel.value.maintainerName || 
      !recordFormModel.value.maintenanceTime || 
      !recordFormModel.value.maintenanceContent) {
    ElMessage.warning('请填写完整信息')
    return
  }

  try {
    isSubmitting.value = true
    if (recordFormModel.value.cost) {
      recordFormModel.value.cost = Number(recordFormModel.value.cost)
    }

    if (isEdit.value && editingId.value) {
      await maintenanceApi.updateRecord(editingId.value, recordFormModel.value)
      ElMessage.success('修改成功')
    } else {
      await maintenanceApi.addRecord(recordFormModel.value)
      ElMessage.success('维护记录提交成功')
    }
    
    showRecordForm.value = false
    if (activeTab.value === 'history') {
      await fetchMaintenanceRecords()
    } else {
      await fetchMaintenancePlans()
    }
  } catch (error) {
    ElMessage.error('提交失败')
  } finally {
    isSubmitting.value = false
  }
}

const handlePageChange = (page: number) => {
  pageNum.value = page
  activeTab.value === 'upload' ? fetchMaintenancePlans() : fetchMaintenanceRecords()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  activeTab.value === 'upload' ? fetchMaintenancePlans() : fetchMaintenanceRecords()
}

const handleSearch = () => {
  pageNum.value = 1
  activeTab.value === 'upload' ? fetchMaintenancePlans() : fetchMaintenanceRecords()
}

const handleReset = () => {
  searchParams.value = { serialNumber: null, maintainerName: null }
  pageNum.value = 1
  activeTab.value === 'upload' ? fetchMaintenancePlans() : fetchMaintenanceRecords()
}

const handleTabChange = (tab: string) => {
  pageNum.value = 1
  tab === 'history' ? fetchMaintenanceRecords() : fetchMaintenancePlans()
}
</script>
<style lang="scss" scoped>
.card-box {
  width: 100%;
  max-width: 100%;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  padding: 0;
  overflow: hidden;
}

.header {
  padding: 0.8rem 1.2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e6eaf0;
  background-color: #f7f9fc;
  
  h2 {
    font-weight: 600;
    font-size: 1.4rem;
    color: #333;
    user-select: none;
    margin: 0;
  }
}

.filter-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  padding: 12px;
  align-items: center;
  background-color: #f7f9fc;
}

.filter-item {
  margin-bottom: 0 !important;
  flex: 1;
  min-width: 200px;
}

.action-buttons {
  flex: none;
  margin-left: auto;
}

.responsive-table-container {
  overflow-x: auto;
  padding: 0.8rem;
}

.custom-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0 6px;
  font-size: 0.9rem;

  thead tr {
    background-color: #f5f7fa;
    color: #606266;
    font-weight: 600;
  }

  th, td {
    padding: 8px 12px;
    text-align: left;
    vertical-align: middle;
    white-space: nowrap;
  }

  tbody tr {
    background-color: #fff;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    transition: background-color 0.2s ease;

    &:hover {
      background-color: #f4f9ff;
    }
  }

  .truncate {
    max-width: 180px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .action-btns {
    display: flex;
    gap: 0.4rem;

    .el-button {
      padding: 0;
      width: 28px;
      height: 28px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 50%;
    }
  }
}

.pagination-container {
  padding: 0.8rem;
  display: flex;
  justify-content: center;
}

.text-center {
  text-align: center;
}

.py-4 {
  padding-top: 1rem;
  padding-bottom: 1rem;
}

.drawer-form {
  .el-form-item {
    margin-bottom: 1rem;

    label {
      font-weight: 500;
      color: #606266;
    }
  }
}

.el-tag {
  margin-right: 10px;
}

@media (max-width: 768px) {
  .filter-item {
    min-width: 100%;
  }
  
  .action-buttons {
    margin-left: 0;
    width: 100%;
    display: flex;
    justify-content: flex-end;
    gap: 8px;
  }
}
</style>